from django.shortcuts import render
from django.contrib.auth.models import User
from django.conf import settings
from django.core.files.base import ContentFile
from django.db.models import Q, Count
from django.utils import timezone

from rest_framework import generics
from rest_framework.decorators import api_view
from rest_framework.decorators import permission_classes
from rest_framework.decorators import parser_classes
from rest_framework import parsers
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework import serializers
from drf_spectacular.utils import extend_schema, extend_schema_view, OpenApiParameter, inline_serializer
from drf_spectacular.types import OpenApiTypes

from account.models import Account
from account.serializer import AccountSerializer
from core.serializer import ResponseSerializer
from core.response import AppResponse
from system.wechat import CustomStorage

from wechatpy import WeChatClient
from decouple import config

import requests
import random
import uuid
import os



# 账号密码登录
@extend_schema(
    description='账号密码登录',
    request=inline_serializer(
        name="InlineFormSerializer",
        fields={
            "username": serializers.CharField(),
            "password": serializers.CharField(),
        },
    ),
    responses=ResponseSerializer
)
@parser_classes([parsers.MultiPartParser])
@api_view(['POST'])
@permission_classes([AllowAny])
def password_login(request):
    username = request.data.get("username", None)
    password = request.data.get("password", None)
    if username == None:
        return AppResponse(message="please enter user username", code=1)
    if password == None:
        return AppResponse(message="please enter user password", code=1)
    user = User.objects.filter(username=username).first()
    if user == None:
        return AppResponse(message="account not exits", code=1)
    if user.check_password(password):
        token, tc = Token.objects.get_or_create(user=user)
        return AppResponse({"token": token.key})
    return AppResponse(message="passwod not correct", code=1)


# 微信用户登录
@extend_schema(
    description='微信登录', 
    parameters=[
        OpenApiParameter(
            name="code", 
            type=OpenApiTypes.STR, 
            required=True,
            location=OpenApiParameter.QUERY,
            description="微信登录code",
        ),
    ],
    request=None,
    responses=None
)
@api_view(['GET'])
@permission_classes([AllowAny])
def wechat_login(request):
    code = request.query_params.get("code", None)

    if code == None:
        return AppResponse(message="请提供登录code")
    wx_client = WeChatClient(config('WEIXIN_APP_ID'), config('WEIXIN_APP_SECRET'), session=CustomStorage())
    session_info = wx_client.wxa.code_to_session(code)
    openid = session_info['openid']
    session_key = session_info['session_key']
    instance, created = Account.objects.get_or_create(wx_openid=openid)
    if created or instance.user is None:
        user, cu = User.objects.get_or_create(username=openid)
        instance.user = user
        instance.save()
    token, tc = Token.objects.get_or_create(user=instance.user)
    return AppResponse({"token": token.key})


# 用户资料
@extend_schema_view(
    get=extend_schema(
        description='获取用户资料', 
        responses=AccountSerializer
    ),
    post=extend_schema(
        description='更新用户资料', 
        request=inline_serializer(
            name="InlineFormSerializer",
            fields={
                "avatar": serializers.FileField(),
                "nickname": serializers.CharField(),
            },
            required=False,
        ),
        responses=OpenApiTypes.UUID
    ),
)
@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def profile(request):

    account = request.user.account_set.first()
    if request.method == 'POST':
        nickname = request.data.get("nickname", None)
        avatar_file = request.data.get("avatar_file", None)
        avatar_url = request.data.get("avatar_url", None)
        phone = request.data.get("phone", None)
        if nickname != None:
            account.nickname = nickname
        if avatar_url != None:
            r = requests.get(avatar_url)
            isExist = os.path.exists(settings.MEDIA_ROOT + 'avatar/')
            if not isExist:
                os.makedirs(settings.MEDIA_ROOT + 'avatar/')
            if r.status_code == 200:
                account.avatar.save(account.user.username + '.jpg', ContentFile(r.content))
            else:
                print('下载失败', avatar_url)
        if avatar_file != None:
            account.avatar = avatar_file
        if phone != None:
            account.phone = phone
        account.save()
    if account is None:
        account = Account.objects.create(user=request.user)
    serializer = AccountSerializer(account, context={"request": request})
    return AppResponse(serializer.data)

